package com.degon.hsyl.choosefile.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.degon.hsyl.choosefile.bean.FileBean;
import com.degon.hsyl.choosefile.bean.MimeTable;

import java.util.ArrayList;
import java.util.List;

public class GetFileUtil {

    /**
     * 根据文件类型返回全部文件列表
     *
     * @param context 上下文
     * @param types   文件类型，如：doc,docx,xls,xlsx,ppt,pptx,pdf
     * @return 文件列表
     */
    public static List<FileBean> searchByType(Context context, List<String> types) {
        List<FileBean> fileList = new ArrayList<>();
        for (String type : types) {
            for (String[] strings : MimeTable.MIMETable) {
                if (type.equals(strings[0])) {
                    ContentResolver resolver = context.getContentResolver();
                    Uri uri = MediaStore.Files.getContentUri("external");
                    Cursor cursor = resolver.query(uri,
                            new String[]{MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE},
                            MediaStore.Files.FileColumns.MIME_TYPE + " = '" + strings[1] + "'",
                            null, null);
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            FileBean bean = new FileBean();
                            String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA));
                            bean.setType(type);
                            bean.setPath(path);
                            bean.setName(path.substring(path.lastIndexOf("/") + 1));
                            bean.setSize(GetFileSizeUtil.getFileSize(cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE))));
                            fileList.add(bean);
                        }
                    }
                    cursor.close();
                }
            }
        }
        return fileList;
    }

}
